<template>
  <div>
    <el-upload action="#" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
      :file-list="fileList" :on-change="handleChange" :http-request="upload" :before-upload="handleBeforeUpload"
      :limit="1" :class="{disabled : is_show}">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress v-if="is_show_per" :text-inside="true" style="width: 148px;" :stroke-width="13"
      :percentage="Percentage"></el-progress>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import COS from 'cos-js-sdk-v5'
  var cos = new COS({
    SecretId: 'AKIDWqwwgAQRBervlOwJgmbCYeU7WdT3P7an',
    SecretKey: '4rNbbKnzweka9SUHn35rOfiaEg1B7sQk'
  })
  export default {
    data () {
      return {
        fileList: [],    //上传图片数组
        dialogImageUrl: '',
        dialogVisible: false,  //控制上传弹层
        Percentage: 0,   //进度条
        is_show_per: false,    //进度条是否显示
        currentFileUid: ''   //要上传的uid
      };
    },
    computed: {
      is_show () {
        return this.fileList.length == 1
      }
    },
    methods: {
      // 点击删除图片时触发的事件
      handleRemove (file, fileList) {
        this.fileList = this.fileList.filter(item => {
          return item.uid !== file.uid
        })
      },
      // 点击文件列表中已上传的文件时的钩子（本案例中是点击图片触发弹出层事件）
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleChange (file, fileList) {
        // 此方法会执行两次，一次添加文件，一次进行文件上传，若不填写上传文件地址
        //  则会执行上传失败方法，那么这样fileList的长度就会经历从1变为0
        this.fileList = fileList.map(item => {
          return item
        })
      },
      // 进行上传文件时的检查
      handleBeforeUpload (file) {
        // 进行上传文件类型的判断
        this.is_show_per = true
        const isJPG = true
        if (file === '') {
          this.$message.error('头像不能为空')
        }
        const isLt5M = file.size / 1024 / 1024 < 10
        if (!isJPG) {
          this.$message.error('图片类型不符合要求')
        } else if (!isLt5M) {
          this.$message.error('图片大小不能超过5M')
        }
        this.currentFileUid = file.uid
        return isJPG && isLt5M
      },
      // 覆盖默认上传行文，自定义上传事件
      upload (res) {
        cos.putObject({
          Bucket: 'tyk-1307731648',   //存储桶名称
          Region: 'ap-shanghai',  //百度云地区
          Key: res.file.name,   //图片名称
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.Percentage = progressData.percent * 100
          }
        }, (err, data) => {
          if (err) {
            this.$message.error('文件上传失败，请重新上传')
          } else {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, update: true }
              }
              return item
            })
            this.is_show_per = false
            this.Percentage = 0
          }
        })
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .disabled .el-upload--picture-card {
    display: none;
  }
</style>